package com.project.nimsen.web.pub;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import com.project.jdbc.web.BaseMVCAction;
import com.project.nimsen.constant.ModelConstant;
import com.project.nimsen.dto.SiteDto;
import com.project.nimsen.entity.Archives;
import com.project.nimsen.entity.Coltype;
import com.project.nimsen.entity.Modelinfo;
import com.project.nimsen.service.IArchivesService;
import com.project.nimsen.service.IColtypeService;
import com.project.nimsen.service.IModelinfoService;
import com.project.nimsen.service.ISiteService;
import com.project.nimsen.util.NimsenUtil;
/**
 * 首页访问时的action类
 * */
@Controller
@RequestMapping(value ="/pub")
public class FirstGuestControl extends BaseMVCAction {
	@Resource
	IColtypeService coltypeService;
	@Resource
	IArchivesService archivesService;
	@Resource
	ISiteService siteService;
	@Resource
	IModelinfoService modelinfoService;
	@RequestMapping(value ="/index")
	public String index(HttpServletRequest request){
		String result;
		try {
			//处理站点信息
			result = checkSite(request);
			if(!StringUtils.isEmpty(result))
				return result;
			result =  returnURLpath("index", request);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return "/themes/index";
	}
	/**
	 * 得到应该返回的模板信息,放到session中
	 * */
	private void searchModel(HttpServletRequest request)throws Exception{
		HttpSession session = request.getSession();
		//用户访问的终端
		String access_terminal = NimsenUtil.obj2String(session.getAttribute("access_terminal"));
		//如果是平板端的情况
		if(ModelConstant.PAD.equals(access_terminal)){
			String modelname = modelbyterminal(request, "padmodelid", session);
			if(!StringUtils.isEmpty(modelname))
				return;
			modelname = modelbyterminal(request, "phonemodelid", session);
			if(!StringUtils.isEmpty(modelname))
				return;
			modelname = modelbyterminal(request, "modelid", session);
			if(!StringUtils.isEmpty(modelname))
				return;
		}
		//如果是手机端的情况
		if(ModelConstant.PHONE.equals(access_terminal)){
			String modelname = modelbyterminal(request, "phonemodelid", session);
			if(!StringUtils.isEmpty(modelname))
				return;
			modelname = modelbyterminal(request, "padmodelid", session);
			if(!StringUtils.isEmpty(modelname))
				return;
			modelname = modelbyterminal(request, "modelid", session);
			if(!StringUtils.isEmpty(modelname))
				return;
		}
		//如果是pc端的情况
		if(ModelConstant.PC.equals(access_terminal)){
			String modelname = modelbyterminal(request, "modelid", session);
			if(!StringUtils.isEmpty(modelname))
				return;
			modelname = modelbyterminal(request, "padmodelid", session);
			if(!StringUtils.isEmpty(modelname))
				return;
			modelname = modelbyterminal(request, "phonemodelid", session);
			if(!StringUtils.isEmpty(modelname))
				return;
		}
//		String modelname = modelbyterminal(request, "modelid", session);
//		if(!StringUtils.isEmpty(modelname))
//			return;
//		modelname = modelbyterminal(request, "padmodelid", session);
//		if(!StringUtils.isEmpty(modelname))
//			return;
//		modelname = modelbyterminal(request, "phonemodelid", session);
//		if(!StringUtils.isEmpty(modelname))
//			return;
	}
	//得到用户访问模板方法的抽取
	private String modelbyterminal(HttpServletRequest request, String property, HttpSession session)throws Exception{
		if(session.getAttribute("pub_site")==null)
			checkSite(request);
		Map<String,Object> site = (Map<String, Object>) session.getAttribute("pub_site");
		String modelid = NimsenUtil.obj2String(site.get(property));
		if(!StringUtils.isEmpty(modelid)){
			Modelinfo model = modelinfoService.findEntityById(modelid);
			if(model!=null){
				session.setAttribute("access_model", model);
				return model.getModelname();
			}
		}
		return null;
	}
	/**
	 * 处理请求的站点信息
	 * */
	private String checkSite(HttpServletRequest request) throws Exception{
		//用户访问的站点名称
		HttpSession session = request.getSession();
		if(session.getAttribute("pub_siteid")==null){
			String domename = request.getServerName();
			SiteDto dto = new SiteDto();
			dto.setDomainname(domename);
			Map<String,Object> site = siteService.findByDto(dto);
			if(site==null)
				return "/error/404";
			session.setAttribute("pub_siteid", site.get("id").toString());
			session.setAttribute("pub_site", site);
		}
		return null;
	}
	/**
	 * 要返回路径的类型
	 * @param pathtype 值为index表示首页,col表示栏目或者详细页面
	 * */
	private String returnURLpath(String pathType, HttpServletRequest request)throws Exception{
		//得到相应的模板信息
		HttpSession session = request.getSession();
		if(session.getAttribute("access_model")==null)
			searchModel(request);
		Modelinfo model = (Modelinfo) session.getAttribute("access_model");
		if(model==null)
			return "/error/404";
		//当访问首页的时候
		if("index".equals(pathType)){
			//站点信息
			Map<String,Object> site = (Map<String, Object>) session.getAttribute("pub_site");
			String modelid = model.getId();
			if(modelid.equals(NimsenUtil.obj2String(site.get("modelid")))){
				String page = NimsenUtil.obj2String(site.get("indexmodel"));
				return "/themes/"+model.getModelname()+"/"+page.substring(0, page.lastIndexOf("."));
			}
			if(modelid.equals(NimsenUtil.obj2String(site.get("phonemodelid")))){
				String page = NimsenUtil.obj2String(site.get("phoneindexmodel"));
				return "/themes/"+model.getModelname()+"/"+page.substring(0, page.lastIndexOf("."));
			}
			if(modelid.equals(NimsenUtil.obj2String(site.get("padmodelid")))){
				String page = NimsenUtil.obj2String(site.get("padindexmodel"));
				return "/themes/"+model.getModelname()+"/"+page.substring(0, page.lastIndexOf("."));
			}
		}
		//当访问栏目的时候
		if("col".equals(pathType)){
			//去掉两边的"/"符号
			String url = request.getServletPath();
			//处理前面的url
			String columnAllUrl = url.substring(8);///pub/col
			boolean isDetailPage = false;//用于记录是否为详细页面
			//判断是内容页面还是列表页面
			String columUrl = "";
			//处理站点信息
			String result = checkSite(request);
			if(!StringUtils.isEmpty(result))
				return result;
			if(columnAllUrl.indexOf(".")>0&&".html".equals(columnAllUrl.substring(columnAllUrl.lastIndexOf(".")))){
				columUrl = columnAllUrl.substring(0, columnAllUrl.lastIndexOf("/"));
				String archUrl = columnAllUrl.substring(columnAllUrl.lastIndexOf("/")+1);
				String archid = archUrl.substring(0, archUrl.lastIndexOf("."));
				//设置文章id
				request.setAttribute("archid", archid);
				//文档的基本信息
				Archives arch = archivesService.findEntityById(archid);
				if(arch==null)
					return "/error/404";
				request.setAttribute("arch", arch);
				isDetailPage = true;
			}else
				columUrl = StringUtils.trimTrailingCharacter(columnAllUrl, '/');
			//当前栏目的信息
			String siteid = NimsenUtil.obj2String(session.getAttribute("pub_siteid"));
			Coltype col= coltypeService.findEntityByVurl(columUrl, siteid);
			if(col==null||StringUtils.isEmpty(col.getArchivesmodel())||
				StringUtils.isEmpty(col.getListmodel()))
				return "/error/404";
			request.setAttribute("coltypeid", col.getId());
			//判断模版类型
			StringBuffer pathsbf = new StringBuffer(model.getModelname());
			String modelType = model.getModel();
			String page = "";
			//是否是详细页面
			if(isDetailPage){
				//如果是平板端的情况
				if(ModelConstant.PAD.equals(modelType))
					page = col.getPadarchmodel();
				//如果是手机端的情况
				if(ModelConstant.PHONE.equals(modelType))
					page = col.getPhonearchmodel();
				//如果是pc端的情况
				if(ModelConstant.PC.equals(modelType))
					page = col.getArchivesmodel();
			}else{
				//如果是平板端的情况
				if(ModelConstant.PAD.equals(modelType))
					page = col.getPadlistmodel();
				//如果是手机端的情况
				if(ModelConstant.PHONE.equals(modelType))
					page = col.getPhonelistmodel();
				//如果是pc端的情况
				if(ModelConstant.PC.equals(modelType))
					page = col.getListmodel();
			}
			pathsbf.append("/").append(page.substring(0, page.lastIndexOf(".")));
			return "/themes/"+pathsbf.toString();
		}
		return "/error/404";
	}
	@RequestMapping(value ="/col/**/*")
	public String colall(HttpServletRequest request){
		//如果有颁布信息则把分页信息存起来
		request.setAttribute("pageIndex", getIntegerParameter("pageIndex"));
		try {
			return returnURLpath("col", request);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return "/themes/index";
	}
	@RequestMapping(value ="/file")
	public void file(HttpServletRequest request,HttpServletResponse response){
		try {
//			ZxingUtil.encodePR("BEGIN:VCARD \nVERSION:3.0 \nN:杜说 \nEMAIL:accpdubing@gmail.com \nTEL:18103896062 \nTEL;CELL:18103896062 \nADR;WORK:河南省济源市 \nORG:济源微盟 \nTITLE:技术员 \nURL:http://www.f273c.com \nNOTE:多断镜子芳 \nEND:VCARD", 600, 600, response.getOutputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
